var id_main_tabs = '#main-tabs';
var id_editor_tabs = '#editor-tabs';
var instance_name = 'data-editor';

/**
 * 设置Html编辑器内容
 * @param {Event} event 事件实例
 * @param {String} content 需要预览的内容(html)
 */
function setHtmlEditorContent(event, content) {
    var $elem = $(event.target).parents('#doc-list [data-id]');
    var id = $elem.attr('data-id'),
        title = $elem.find('.line-title').text().trim();
    var tags = [];
    console.log('parse tags');
    $elem.find('.line-tags').children('strong').each(function(i, tag) {
        // parse tags
    });
    $('#doc-title').val(title);
    $('#doc-save').attr('data-id', id);
    var editor = $('#html-editor').data('editor');
    editor.setValue(content);
}

/**
 * 预览内容
 * @param  {Event} event  需要预览的内容(html)
 * @param  {jQuery Element Object} mainTabs 主选项卡
 */
function previewContent(event, mainTabs) {
    var content = $(event.target).attr('data-content');
    var perview_index = $('#tab-perview').index('.main-tabs-content > .c-tab');
    var iframe = document.getElementById('doc-preview');
    var doc = iframe.contentDocument ?
        iframe.contentDocument :
        (
            iframe.contentWindow ?
                iframe.contentWindow.document :
                iframe.document
        );
    var preview_css = $('#preview-css').html().trim(),
        preview_js = $('#preview-js').html().trim();
    doc.open("text/html", "replace");
    doc.write([
        '<!DOCTYPE html>',
        '<html>',
            '<head>',
                '<base target="_blank" />',
                '<meta charset="utf-8" />',
                '<style type="text/css">',
                    preview_css,
                '</style>',
            '</head>',
            '<body>',
                '<div class="content-wrapper">',
                    content,
                '</div>',
                '<script type="text/javascript">',
                    preview_js,
                '</script>',
            '</body>',
        '</html>'
    ].join(''));
    doc.close();
    setHtmlEditorContent(event, content);
    mainTabs.goToTab(perview_index);
    $(window).trigger('resize');
}

/**
 * 调整iframe的高度
 */
function adjustIFrame() {
    var max_height = $('#main').height(),
        link_height = $('#main-tabs .mian-tabs-link').outerHeight(true);
    $('#doc-preview').height(max_height - link_height - 20);
}

/**
 * 调整编辑器高度通用(获取高度的)方法
 */
function adjustEditorCommon() {
    return {
        max_height: $('#main').height(),
        main_link_height: $('#main-tabs .mian-tabs-link').outerHeight(true),
        editor_link_height: $('#editor-tabs .editor-tabs-link').outerHeight(true),
        title_height: Math.max($('#doc-save').outerHeight(true), $('#doc-title').outerHeight(true))
    };
}

/**
 * 调整MarkDown编辑器的高度
 */
function adjustMarkDownEditor() {
    var hs = adjustEditorCommon();
    var max_height = hs['max_height'],
        main_link_height = hs['main_link_height'],
        editor_link_height = hs['editor_link_height'],
        title_height = hs['title_height'];
    // console.log(max_height, main_link_height, editor_link_height, title_height);
    console.log('TODO: adjust markdown editor height')
}

/**
 * 调整Html编辑器的高度
 */
function adjustHtmlEditor() {
    var hs = adjustEditorCommon();
    var max_height = hs['max_height'],
        main_link_height = hs['main_link_height'],
        editor_link_height = hs['editor_link_height'],
        title_height = hs['title_height'];
    var toolbar_height = $('#wysihtml-editor-toolbar').height();
    var margin_top = $('#html-editor iframe.wysihtml-sandbox').css('margin-top');
    margin_top = parseInt(margin_top.replace('px', ''));
    var available_height = max_height - (main_link_height + editor_link_height + title_height + toolbar_height + margin_top);
    var $wrapper = $('#html-editor .editor-wrapper');
    available_height -= Math.round(margin_top / 2 + 0.5);
    $wrapper.height(available_height);
    $wrapper.css('margin-bottom', margin_top);
}

$(document).ready(function() {
    /////////////////////// menu ///////////////////////////////////////
    $(document).click(function(e) {
        e.preventDefault();
        var $menu = $('.menu-wrapper');
        var click_in = (
            $menu.is(e.target) ||
            $menu.has(e.target).length > 0
        );
        if(!click_in) {
            hideMenu($menu);
        }
    });
    $(document).keydown(function(e) {
        var key = e.keyCode || e.which;
        // ESC
        if(key == 27) {
            var $menu = $('.menu-wrapper');
            hideMenu($menu);
        }
    });
    $('.menu-wrapper').off('click').on('click', function(e) {
        var $elem = $(e.target);
        if($elem.parent().hasClass('menu-item')) {
            $elem = $elem.parent();
        }
        if($elem.length > 0 && $elem.hasClass('menu-item')) {
            var action = $elem.attr('data-action');
            var $menu = $('.menu-wrapper');
            var action_data = $menu.data('action-data');
            action_data['action'] = action;
            action_data['menu'] = $menu;
            handleAction(action_data);
        }
    });

    /////////////////////// tree ///////////////////////////////////////
    $.fn.zTree.init($('#' + GLOBAL.TREE_ID), setting);

    var tree_obj = $.fn.zTree.getZTreeObj(GLOBAL.TREE_ID);

    /////////////////////// tabs ///////////////////////////////////////
    var mainTabs = tabs({
        el: id_main_tabs,
        tabNavigationLinks: '.mian-tabs-link > .c-tabs-nav__link',
        tabContentContainers: '.main-tabs-content > .c-tab',
        activeChanged: function(index, tabNavigationLinks, tabContentContainers) {
            var link = tabNavigationLinks[index],
                container = tabContentContainers[index];
            // console.log(link);
            // console.log(container);
            if($(container).attr('id') == 'tab-editing') {
                if($('#markdown-editor').hasClass('is-active')) {
                    adjustMarkDownEditor();
                }
                else if($('#html-editor').hasClass('is-active')) {
                    adjustHtmlEditor();
                }
            }
        }
    });
    mainTabs.init();
    $(id_main_tabs).data(instance_name, mainTabs);
    
    var editorTabs = tabs({
        el: '#editor-tabs',
        tabNavigationLinks: '.editor-tabs-link > .c-tabs-nav__link',
        tabContentContainers: '.editor-tabs-content > .c-tab',
        activeChanged: function(index, tabNavigationLinks, tabContentContainers) {
            var link = tabNavigationLinks[index],
                container = tabContentContainers[index];
            if($(container).attr('id') == 'markdown-editor') {
                adjustMarkDownEditor();
            }
            else if($(container).attr('id') == 'html-editor') {
                adjustHtmlEditor();
            }
        }
    });
    editorTabs.init();
    $(id_editor_tabs).data(instance_name, editorTabs);
    // var markdown_index = $('#markdown-editor').index('.editor-tabs-content > .c-tab');
    // editorTabs.goToTab(markdown_index); // 选项卡索引，从0开始

    /////////////////////// editor ///////////////////////////////////////
    var editor = new wysihtml.Editor("wysihtml-textarea", { // id of textarea element
        stylesheets: [
            '/static/lib/wysihtml/css/editor.css'
        ],
        toolbar: "wysihtml-editor-toolbar", // id of toolbar element
        parserRules: wysihtmlParserRules // defined in parser rules set 
    });
    editor.on("load", function() {
        var composer = editor.composer;
        var a = composer.element.querySelector("a");
        if(a) {
            composer.selection.selectNode(a);
        }
        // console.log('editor loaded')
    });
    $('#html-editor').data('editor', editor);

    $('#doc-save').off('click').on('click', function() {
        var folder = null;
        var nodes = tree_obj.getSelectedNodes();
        if(nodes.length > 0) {
            folder = nodes[0].id;
        }

        var title = $('#doc-title').val(),
            content = editor.getValue();
        saveNewDoc(title, content, folder);
    });

    $('#doc-list').off('click').on('click', '[data-id] .line-content a[data-content]', function(e) {
        previewContent(event, mainTabs);
    });

    // 高度调整
    $(window).off('resize').on('resize', function() {
        $('#sidebar').css('height', '100vh');
        adjustMainWidth();
        adjustIFrame();
        adjustHeight();
    });

    $(window).trigger('resize');

    // 导航可变宽度
    resizable();
});